package com.sunxd.rule.judge.handler;

import com.alibaba.fastjson.JSON;
import com.sunxd.rule.judge.beans.enums.OperatorTypeEnum;
import com.sunxd.rule.judge.beans.param.Condition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * 1 在 【1，2】 或 【2，1】 区间内
 * support  int,double,long, date
 */
@Slf4j
@Component
public class GTE_LTEConditionHandler extends AbsConditionHandler {

    @Override
    public Boolean doJudge(Condition condition) {
        Object right = condition.getRight();
        if (right instanceof Collection) {
            Collection<Object> collection = (Collection<Object>) right;
            int size = collection.size();
            if (size != 2) {
                return Boolean.FALSE;
            }
            return checkASCCollection(condition.getLeft(),collection) || checkDESCCollection(condition.getLeft(),collection);
        } else {
            log.error("Does not conform to the configuration format.  eg:[a,b] , param : {}", JSON.toJSONString(condition));
            return Boolean.FALSE;
        }
    }

    @Override
    public String operatorType() {
        return OperatorTypeEnum.GTE_LTE.name();
    }

    public boolean checkASCCollection(Object left, Collection<Object> collection){
        Iterator<Object> iterator = collection.iterator();
        return  conditionJudge.gte(left,iterator.next()) &&  conditionJudge.lte(left,iterator.next());
    }

    public boolean checkDESCCollection(Object left, Collection<Object> collection){
        Iterator<Object> iterator = collection.iterator();
        return  conditionJudge.lte(left,iterator.next()) &&  conditionJudge.gte(left,iterator.next());
    }


}
